package com.zzg.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.zzg.author.condition.RoleCondition;
import com.zzg.author.model.domain.SysRole;
import com.zzg.author.service.SysRoleService;
import com.zzg.author.service.SysUserService;
import com.zzg.author.shrio.service.ShiroService;
import com.zzg.base.response.BaseResponse;
import com.zzg.base.response.PageResponse;
import com.zzg.util.result.ResultUtil;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(value = "角色", description = "角色管理")
@Controller
@RequestMapping("/role")
@Slf4j
public class RoleController {
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private ShiroService shiroService;
	@Autowired
	private SysUserService sysUserService;

	/** 角色列表 **/
	@ApiOperation(value = "资源列表", notes = "资源列表")
	@RequiresPermissions("roles")
	@GetMapping("/role")
	public ModelAndView role() {
		return ResultUtil.view("admin/role/role");
	}

	@RequiresPermissions("role:list")
	@PostMapping("/list")
	@ResponseBody
	public PageResponse list(RoleCondition vo) {
		PageInfo<SysRole> pageInfo = sysRoleService.findPageBreakByCondition(vo);
		return ResultUtil.tablePage(pageInfo);
	}

	/***
	 * 添加角色
	 * 
	 * @return
	 */
	@ApiOperation(value = "添加角色", notes = "添加角色")
	@GetMapping("/add")
	public ModelAndView add() {
		log.info("[role-add-page]-[{}]", "测试210");
		return ResultUtil.view("admin/role/add");
	}

	@RequiresPermissions("role:add")
	@PostMapping("/add")
	@ResponseBody
	public BaseResponse add(SysRole sysRoleForm) {
		try {
			sysRoleForm.setCreatetime(DateUtil.date());
			sysRoleForm.setUpdatetime(DateUtil.date());
			sysRoleForm.setRoleId(RandomUtil.randomUUID().substring(0, 7).toString());
			if (sysRoleService.insert(sysRoleForm)) {
				return ResultUtil.success("角色添加成功！");
			} else {
				return ResultUtil.error("角色添加失败！");
			}
		} catch (Exception e) {
			log.error("[角色添加失败！]-[{}]", e.getMessage());
			return ResultUtil.error("角色添加失败！");
		}
	}

	/***
	 * 编辑角色
	 * 
	 * @param id
	 * @param map
	 * @return
	 */
	@ApiOperation(value = "编辑角色", notes = "编辑角色")
	@GetMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable("id") Integer id, ModelMap map) {
		map.addAttribute("role", sysRoleService.selectById(id));
		return ResultUtil.view("admin/role/edit");
	}

	@RequiresPermissions("role:edit")
	@PostMapping("/edit")
	@ResponseBody
	public BaseResponse edit(SysRole sysRole) {
		sysRole.setUpdatetime(DateUtil.date());
		sysRole.setRoleId(RandomUtil.randomUUID().substring(0, 7).toString());
		if (sysRoleService.updateById(sysRole)) {
			return ResultUtil.success("角色修改成功！");
		} else {
			return ResultUtil.error("角色修改失败！");
		}
	}

	/***
	 * 角色分配资源
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@ApiOperation(value = "角色分配资源", notes = "角色分配资源")
	@GetMapping("/rule/{id}")
	public ModelAndView rule(@PathVariable("id") Integer id, Model model) {
		model.addAttribute("id", id);
		return ResultUtil.view("admin/role/rule");
	}

	@RequiresPermissions("role:assign")
	@PostMapping("/assign")
	@ResponseBody
	public BaseResponse assign(String id, String[] menuIds) {
		System.out.println(menuIds + "--------" + id);
		List<String> resourceIds = new ArrayList<>();
		if (menuIds.length != 0) {
			resourceIds = Arrays.asList(menuIds);
		}
		BaseResponse responseVo = sysRoleService.addAssignResourceById(id, resourceIds);
		// 重新加载拥有角色的资源权限
		shiroService.reloadAuthorizingByRoleId(Convert.convert(Integer.class, id));
		return responseVo;
	}

	/***
	 * 删除角色
	 * 
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "删除角色", notes = "删除角色")
	@RequiresPermissions("role:delete")
	@PostMapping("/delete/{id}")
	@ResponseBody
	public BaseResponse delete(@PathVariable("id") Integer id) {
		if (sysUserService.findByRoleId(id).size() > 0) {
			return ResultUtil.error("当前角色存在用户，不能删除！");
		}
		if (sysRoleService.deleteById(id)) {
			return ResultUtil.success("角色删除成功！");
		} else {
			return ResultUtil.error("角色删除失败！");
		}
	}
}
